package com.demo.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.parser.XmlTreeBuilder;
import org.jsoup.select.Elements;

/**
 * HTML相关处理
 * HTML分析
 * URL编码/解码
 * URL转码
 * @author ryuu.kk
 *
 */
public final class HtmlUtils {

	//private class
	private HtmlUtils() {
		
	}
	
	public static String parse(URL url) {
		
		return "";
	}
	
	public static String xmlParse(InputStream input, String encoding, String baseUri) throws IOException {
		Jsoup.parse(input, encoding, encoding, new Parser(new XmlTreeBuilder()));
		return "";
	}
	
	/**
	 * 根据属性参数,对HTML进行分解
	 * 属性所在的内容将被移除
	 * @param html 输入的HTML内容
	 * @param arrtibute 分解标示(Tag属性)
	 * @return 分解后的内容
	 */
	public static List<String> htmlParse(String html, String arrtibute) {
		Document document = Jsoup.parse(html);
		if (document.isBlock()) {
			return null;
		}
		List<String> contentList = new ArrayList<String>();
		Elements elements = document.getElementsByAttribute(arrtibute);

		if (elements.isEmpty()) {
			//不存在分页符
			Iterator<Element> is = document.body().children().iterator();
			String singleHtml = "";
			while(is.hasNext()) {
				Element e = is.next();
				singleHtml += e.outerHtml();
			}
			contentList.add(singleHtml);
			return contentList;
		}
		//取得分隔符
		Element splitPage = elements.listIterator().next();
		//取得分隔符的所有同辈元素
		Elements siblings = splitPage.siblingElements();
		ListIterator<Element> pages = siblings.listIterator();
		
		String elementHtml = "";
		while(pages.hasNext()) {
			Element page = pages.next();
			//index = page.siblingIndex();
			if (page.hasAttr(arrtibute) && !StringUtil.isBlank(elementHtml)) {
				// 该同辈元素是一个分隔符Page,并且不是分隔符之间存在内容
				contentList.add(elementHtml);
				elementHtml = "";
				continue;
			}
			String outerHtml = page.outerHtml();
			elementHtml += outerHtml;
		}
		
		if (!StringUtil.isBlank(elementHtml)) {
			contentList.add(elementHtml);
		}
		elementHtml = "";
		return contentList;
	}
	
	
	/**
	 * 对HTML内容进行转义
	 * @param html HTML内容
	 * @return String 转义后的HTML
	 */
	public static String htmlEncode(String html) {
		Document document = Jsoup.parse(html);
		if (document.isBlock()) {
			return "";
		}
		// 补全HTML & 转义其内容
		html = document.html().replace("<", "&lt;")
			.replace(">", "&gt;")
			.replace("&", "&amp;")
			.replace(" ", "&nbsp;")
			.replace("\"", "&quot;");
		
		return html;
	}
	
	/**
	 * 对HTML内容进行转义
	 * @param html HTML内容
	 * @return String 转义后的HTML
	 */
	public static String htmlDecode(String html) {
		
		if (StringUtils.isEmpty(html)) {
			return "";
		}
		// 转义其内容
		html = html.replace("&lt;", "<")
			.replace("&gt;", ">")
			.replace("&amp;", "&")
			.replace("&nbsp;", " ")
			.replace("&quot;", "\"");
		Document document = Jsoup.parse(html);
		if (document.isBlock()) {
			return "";
		}
		// 补全HTML
		return document.html();
	}
	
	/**
	 * 对HTML内容进行过滤
	 * @param html html输入源
	 * @return 去掉HTML标签的输出源
	 */
	public static String htmlRemove(String html) {
		String content = "";
		Document document = Jsoup.parse(html);
		if (document.hasText()) {
			content = document.text();
		}
		return content;
	}
	
	public static void main(String[] args) {
		String str = "<p><strike><u><em>哈哈哈哈哈</em></u></strike></p><div page=\"true\" style=\"page-break-after: always;\"><span style=\"display: none;\">[page]&nbsp;[/page]</span></div><p>	<strong>啊啊啊啊啊啊啊啊啊啊</strong></p><div page=\"true\" style=\"page-break-after: always;\">	<span style=\"display: none;\">[page]&nbsp;[/page]</span></div><p>	<span style=\"color:#daa520;\"><span style=\"background-color: rgb(0, 255, 0);\">3232121121321</span></span></p><div page=\"true\" style=\"page-break-after: always;\">	<span style=\"display: none;\">[page]&nbsp;[/page]</span></div><p>	&nbsp;</p>";
		
		//String str = "<div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>";
		
		List<String> result = HtmlUtils.htmlParse(str, "page");
		
		for (String s : result) {
			System.out.println("\t-----" + s + "\t--------");
		}
		
		System.out.println("-----\t" + HtmlUtils.htmlRemove(str) + "\t--------");
	}
	
	/**
     * 转换编码
     * @param text 输入内容
     * @param oEncoding 内容编码
     * @param nEncoding 转换编码
     * @return 输出内容
     */
	public static String textEncoding(String text, String oEncoding, String nEncoding) {
		String result = "";
		try {
			result = new String(text.getBytes(oEncoding), nEncoding);
		} catch (UnsupportedEncodingException ex) {
			result = ex.toString();
		}
		return result;
	}
	
	/**
	 * url编码
	 * @param text 输入内容
	 * @param encoding 编码：utf-8
	 * @return String
	 */
	public static String urlEncode(String text, String encoding) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			if (c >= 0 && c <= 255) {
				result.append(c);
			} else {
				byte[] b = new byte[0];
				try {
					b = Character.toString(c).getBytes(encoding);
				} catch (Exception ex) {
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					result.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return result.toString();
	}
	
	/**
	 * url地址解码
	 * @param text url地址
	 * @return String解码url
	 */
	public static String urlDecode(String text) {
		String result = "";
		int p = 0;
		if (text != null && text.length() > 0) {
			text = text.toLowerCase();
			p = text.indexOf("%e");
			if (p == -1)
				return text;
			while (p != -1) {
				result += text.substring(0, p);
				text = text.substring(p, text.length());
				if (text == "" || text.length() < 9)
					return result;
				result += CodeToWord(text.substring(0, 9));
				text = text.substring(9, text.length());
				p = text.indexOf("%e");
			}
		}
		return result + text;
	}
	
	/**
	 * utf8URL编码转字符
	 * 如果是UTF-8编码,自动转换
	 * 其他编码则直接返回
	 * @param text 输入text
	 * @return String
	 */
	private static String CodeToWord(String text) {
		String result;
		if (Utf8codeCheck(text)) {
			byte[] code = new byte[3];
			code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256);
			code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256);
			code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256);
			try {
				result = new String(code, "UTF-8");
			} catch (UnsupportedEncodingException ex) {
				result = null;
			}
		} else {
			result = text;
		}
		return result;
	}

	/**
	 * 编码是否有效
	 * 
	 * @param text
	 * @return
	 */
	private static boolean Utf8codeCheck(String text) {
		String sign = "";
		if (text.startsWith("%e"))
			for (int i = 0, p = 0; p != -1; i++) {
				p = text.indexOf("%", p);
				if (p != -1)
					p++;
				sign += p;
			}
		return sign.equals("147-1");
	}

	/**
	 * 是否Utf8Url编码
	 * 
	 * @param text
	 * @return
	 */
	public static boolean isUtf8Url(String text) {
		text = text.toLowerCase();
		int p = text.indexOf("%");
		if (p != -1 && text.length() - p > 9) {
			text = text.substring(p, p + 9);
		}
		return Utf8codeCheck(text);
	}
}
